package com.jintoufs.store.rest;

import com.jintoufs.domain.user.User;
import com.jintoufs.service.user.UserService;
import org.apache.commons.lang.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SupportAction {
	@Resource
	private UserService userService;
	/**
	 * 获得String类型请求参数
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public String getString(HttpServletRequest request, String name) {
		if (StringUtils.isNotEmpty(name)) {
			return request.getParameter(name);
		}
		return null;
	}

	/**
	 * 获得Integer类型请求参数
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public int getInteger(HttpServletRequest request, String name) {
		String value = getString(request, name);
		if (StringUtils.isNotEmpty(value)) {
			try {
				return Integer.parseInt(value);
			} catch (Exception e) {
				return 0;
			}

		}
		return 0;
	}

	/**
	 * 获得Double类型请求参数
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public double getDouble(HttpServletRequest request, String name) {
		String value = getString(request, name);
		if (StringUtils.isNotEmpty(value)) {
			try {
				return Double.parseDouble(value);
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}

		}
		return 0;
	}

	/**
	 * 获得Boolean类型请求参数
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public boolean getBoolean(HttpServletRequest request, String name) {
		String value = getString(request, name);
		if (StringUtils.isNotEmpty(value)) {
			try {
				return Boolean.getBoolean(value);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}

		}
		return false;
	}


	public String formatDate(Date date) {
		String dateStr = null;
		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateStr = sdFormat.format(date);
		return dateStr;
	}

	public Date parseString(String time) throws ParseException {
		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
		return sdFormat.parse(time);
	}

	public User getUserFromClient(String keyStr){
		Map<String, Object> params = new HashMap<>();
		params.put("keyStr", keyStr);
		List<User> userList = userService.queryByParams(params);
		if (userList.isEmpty()) {
			return null;
		}
		return userList.get(0);
	}

	public boolean isUserValid(String keyStr){
		Map<String, Object> params = new HashMap<>();
		params.put("keyStr", keyStr);
		List<User> userList = userService.queryByParams(params);
		if (userList.isEmpty()) {
			return false;
		}
		return true;
	}
}
